package com.azt.provider.impl;

import com.azt.api.dto.EnqQuoteDetail;
import com.azt.api.pojo.*;
import com.azt.api.service.EnqQuoteService;
import com.azt.api.service.ProCategoryService;
import com.azt.api.service.ProRepositoryService;
import com.azt.model.page.Pagination;
import com.azt.provider.mapper.EnqQuoteItemMapper;
import com.azt.provider.mapper.EnqQuoteMapper;
import com.azt.utils.MyStringUtils;
import com.azt.utils.PasswordUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by Snowler on 2016/10/12.
 */
@Service
@Transactional
public class EnqQuoteServiceImpl  implements EnqQuoteService{

    @Autowired
    private EnqQuoteMapper eqm;

    @Autowired
    private EnqQuoteItemMapper eqim;

    @Autowired
    private ProRepositoryService repositoryService;
    @Autowired
    private ProCategoryService categoryService;
    @Override
    public void saveOrUpdateQuote(EnqQuote quote) {
        if (quote.getId() != null) {
            eqm.updateByPrimaryKey(quote);
            if (CollectionUtils.isNotEmpty(quote.getItem())) {
                for (EnqQuoteItem enqQuoteItem : quote.getItem()) {
                    this.eqim.insert(enqQuoteItem);
                }
            }
        } else {
            eqm.insert(quote);
            if (quote.getItem() != null && quote.getItem().size() > 0) {
                for (EnqQuoteItem enqQuoteItem : quote.getItem()) {
                    enqQuoteItem.setQuoteId(quote.getId());
                    this.eqim.insert(enqQuoteItem);
                }
            }
        }
    }

    @Override
    public EnqQuote getCanEditQuoteById(Integer quoteId){
        return quoteId == null ? null : eqm.getCanEditQuoteById(quoteId);
    }

    @Override
    public List<EnqQuoteItem> getItemByQuote(Integer quoteId) {
        return quoteId == null ? null : eqim.getItemByQuote(quoteId);
    }

    @Override
    public void updateQuoteWithDelItem(EnqQuote quote, List<Integer> items , boolean delItems) {

        Example exp = new Example(EnqQuoteItem.class);
        if(delItems){
            exp.createCriteria().andEqualTo("quoteId" , quote.getId());
            eqim.deleteByExample(exp);
        }else if(CollectionUtils.isNotEmpty(items)){
            exp.createCriteria().andEqualTo("quoteId" , quote.getId()).andNotIn("id" , items);
            eqim.deleteByExample(exp);
        }
        this.saveOrUpdateQuote(quote);
    }

	@Override
	public Pagination getQuoteDetail(int pageNo, int pageSize, Integer projectId) {
		Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
		List<EnqQuoteDetail> enqProjectItem = eqm.getQuoteDetail(projectId);
		Pagination p = new Pagination(startPage,enqProjectItem);
		p.setList(enqProjectItem);
		return p;
	}

	@Override
	public Pagination getOrderDetail(int pageNo, int pageSize, Integer projectId) {
		Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
		List<EnqQuoteDetail> orderItem = eqm.getOrderDetail(projectId);
		Pagination p = new Pagination(startPage,orderItem);
		p.setList(orderItem);
		return p;
	}

	@Override
	public EnqQuoteItem getQuoteItemById(int itemId) {
        EnqQuoteItem quoteItem = new EnqQuoteItem();
        quoteItem.setId(itemId);
        return eqim.selectByPrimaryKey(itemId);
    }

    @Override
    public void saveOrUpdateQuoteItem(Integer quoteid, List<EnqQuoteItem> item) {
        EnqQuote quote = eqm.getQuoteByid(quoteid);

        //先删除原有报价
        EnqQuoteItem quoteItem = new EnqQuoteItem();
        quoteItem.setQuoteId(quoteid);
        eqim.delete(quoteItem);

        //quote 表总价
        BigDecimal totalprice = new BigDecimal(0);

        //插入新出的报价item
        for (EnqQuoteItem i : item) {
            i.setQuoteId(quoteid);
            i.setProjectId(quote.getProjectId());
            i.setEnquiryId(quote.getEnquiryId());
            Double quantity = i.getQuantity();
            quantity = quantity==null?0:quantity;
            Double unitprice = i.getUnitprice();
            BigDecimal a =  new BigDecimal(quantity);
            unitprice = unitprice==null?0:unitprice;
            BigDecimal b =  new BigDecimal(unitprice);
            BigDecimal multiply = a.multiply(b);
            totalprice = totalprice.add(multiply);
            i.setTotalPrice(multiply.doubleValue());
            Integer categorySId = i.getCategorySId();
            Integer categoryPId = i.getCategoryPId();
            //如果类目不完善,就去数据库再查
            if(categorySId==null || categoryPId==null){
                Category entity = categoryService.getCategorysById(categoryPId);
                Category topcategory = getTopCategoryByBottomCategory(entity);
                i.setCategorySId(topcategory.getId());
            }
            eqim.insert(i);
        }
        quote.setTotalPrice(totalprice.doubleValue());
        eqm.updateByPrimaryKeySelective(quote);

    }

    @Override
    public void saveOrUpdateRepository(List<EnqQuoteItem> item) {

        // 保存未知系统到数据库
        for (int i = 0; i < item.size(); i++) {
            EnqQuoteItem qitem = item.get(i);
            int needrepository = qitem.getNeedrepository();
            if (needrepository == 1) {// 需要保存到库
                String content = MyStringUtils.replaceBlank(qitem.getProductName());
                String secret = PasswordUtil.MD5_16(content);
                List<ProRepository> repositorys = repositoryService.getRepositoryBymd5(secret);
                if (repositorys == null || repositorys.isEmpty()) {
                    // 不存在
                } else {
                    for (int j = 0; j < repositorys.size(); j++) {
                        ProRepository proRepository = repositorys.get(j);
                        Integer fcateid = qitem.getCategoryPId();
                        // 如果有完成相同的,则不用保存
                        if (proRepository.getProCategory().getId().equals(fcateid)) {
                            // 不需要保存,直接退出
                            return;
                        }
                    }
                }

                ProRepository repository = new ProRepository();
                repository.setTitle(content);
                repository.setSecret(secret);
                repository.setPid(qitem.getCategoryPId());
                repositoryService.saveOrupdateRepository(repository);

            }
        }

    }

    @Override
    public EnqQuote getQuoteById(Integer id) {
        return eqm.getQuoteByid(id);
    }


    private Category getTopCategoryByBottomCategory(Category category) {
        if(category.getPid()==0){
            return category;
        }else{
            Category entity = categoryService.getCategorysById(category.getPid());
            return getTopCategoryByBottomCategory(entity);
        }
    }

    @Override
    public int getQuoteNum(int enquiryId) {
        EnqQuote quote = new EnqQuote();
        quote.setEnquiryId(enquiryId);
        Example example = new Example(EnqQuote.class);
        example.createCriteria().andEqualTo(quote).andNotIn("state", Arrays.asList(0, 2, 3));
        return eqm.selectCountByExample(example);
    }

    @Override
    public Map reference(String name) {
        Map price = null;
        if(StringUtils.isNotBlank(name)){
            price = eqim.reference(name.trim());
        }
        return price;
    }

    @Override
    public List<EnqQuote> getQuoteByEnqidAndStat(Integer enqid,Integer stat) {
        EnqQuote quote  =  new EnqQuote();
        quote.setEnquiryId(enqid);
        quote.setEnquiryId(stat);
        return eqm.select(quote);
    }

    @Override
    public void changeQuteStatFromToByEnqid(Integer enqid, int from, int to) {
        eqm.changeQuteStatFromToByEnqid(enqid,from,to);
    }
}
